package de.htw.praxisprojekt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import de.htw.praxisprojekt.data.AlgoPoint;
import de.htw.praxisprojekt.data.LineFileFilter;

public class LoadSaveAlgoPoints{

	private static final Pattern SEMICON_PATTERN=Pattern.compile(";");

	public static List<AlgoPoint> loadAlgoPoints(File file){
		List<AlgoPoint> algoPoints=new ArrayList<AlgoPoint>();
		String readLine=null;
		BufferedReader reader=null;
		try{
			reader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			while((readLine=reader.readLine())!=null){
				String[] splitLine=SEMICON_PATTERN.split(readLine);
				float x=Float.parseFloat(splitLine[0]);
				float y=Float.parseFloat(splitLine[1]);
				algoPoints.add(new AlgoPoint(x,y));
			}
			reader.close();
		}catch(Exception e){
			System.err.println("Could not load the file: "+file.getName());
			e.printStackTrace();
		}finally{
			try{
				if(reader!=null){
					reader.close();
				}
			}catch(IOException e){
			}
		}
		return algoPoints;
	}

	public static void saveAlgoPoints(File file,List<AlgoPoint> algoPoints){
		if(!file.getName().endsWith(LineFileFilter.LGF_EXTENSION))
			file=new File(file.getAbsolutePath()+LineFileFilter.LGF_EXTENSION);
		BufferedWriter writer=null;
		try{
			writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			for(int i=0;i<algoPoints.size();++i){
				writer.write(algoPoints.get(i).toString());
				if(i!=algoPoints.size()-1)
					writer.newLine();
			}
		}catch(Exception e){
			System.err.println("Could not save the file: "+file.getName());
			e.printStackTrace();
		}finally{
			try{
				if(writer!=null){
					writer.close();
				}
			}catch(IOException e){
			}
		}
	}
}